<template>
  <div class="sql-formatter-page">
    <div class="formatter-container">
      <h1>SQL语句格式化</h1>
      <el-form>
        <el-form-item label="输入SQL语句">
          <div class="editor-wrapper">
            <textarea ref="inputSql" style="text-align: left;"></textarea>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="formatSQL">
            <el-icon><magic-stick /></el-icon>
            格式化
          </el-button>
        </el-form-item>
        <el-form-item label="格式化结果">
          <div class="editor-wrapper">
            <textarea ref="outputSql" style="text-align: left;"></textarea>
          </div>
          <div class="button-group">
            <el-button type="success" @click="copyResult" :disabled="!hasFormattedSQL">
              <el-icon><document-copy /></el-icon>
              复制结果
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <div class="description">
        <h3>关于SQL格式化工具：</h3>
        <ol>
          <li>本工具提供了格式化SQL语句功能，可以美化你的SQL语句，使它更易于阅读和理解。</li>
          <li>支持多种SQL方言，自动缩进和换行，提高代码可读性。</li>
          <li>格式化后的SQL语句可以直接复制使用。</li>
          <li>本工具在浏览器中处理，不会将您的SQL语句上传至服务器，请放心使用。</li>
        </ol>
      </div>
      <div class="button-group">
        <el-button type="warning" @click="goToHomepage">
          <el-icon><back /></el-icon>
          返回
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { MagicStick, DocumentCopy, Back } from '@element-plus/icons-vue'
import CodeMirror from 'codemirror'
import { format } from 'sql-formatter'

// 导入 CodeMirror 样式和模式
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/sql/sql.js'
import 'codemirror/theme/monokai.css'  // 可选：添加主题

const router = useRouter()
const inputSql = ref(null)
const outputSql = ref(null)
const hasFormattedSQL = ref(false)
let inputEditor, outputEditor
let observer = null
let resizeObserver = null

// 添加 mounted 状态变量
let mounted = false

const defaultSQL = `SELECT count(*),Column1,Testing, Testing_Three FROM Table1
WHERE Column1 = 'testing' AND ( (Column2 = Column3 OR Column4 >= NOW()) )
GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10`

// 优化性能的工具函数
const createDeferredPromise = () => {
  let resolve, reject
  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })
  return { promise, resolve, reject }
}

// 优化 RAF 包装器，移除未使用的 rafId
const rafThrottle = (fn) => {
  let isQueued = false
  let lastArgs = null
  
  const run = () => {
    if (!isQueued) return
    if (lastArgs) {
      fn.apply(null, lastArgs)
      lastArgs = null
    }
    isQueued = false
  }

  return (...args) => {
    lastArgs = args
    if (!isQueued) {
      isQueued = true
      requestAnimationFrame(run)
    }
  }
}

// 编辑器配置优化
const getEditorConfig = () => ({
  mode: 'text/x-sql',
  lineNumbers: true,
  theme: 'default',
  lineWrapping: true,
  viewportMargin: 1, // 减小视口边距
  extraKeys: { 'Ctrl-Space': 'autocomplete' },
  alignCDATA: false,
  indentUnit: 4,
  smartIndent: true,
  dragDrop: false,
  workTime: 5, // 减少单次工作时间
  workDelay: 100,
  pollInterval: 300, // 增加轮询间隔
  flattenSpans: true,
  maxHighlightLength: 500, // 减少高亮度限制
  configureMouse: () => ({
    addEventListeners: (node, handleMouse) => {
      const options = { passive: true }
      const events = ['mousedown', 'dragenter', 'touchstart', 'wheel', 'scroll']
      const cleanup = []
      
      events.forEach(event => {
        node.addEventListener(event, handleMouse, options)
        cleanup.push(() => node.removeEventListener(event, handleMouse, options))
      })
      
      return () => cleanup.forEach(fn => fn())
    }
  })
})

const initializeEditors = () => {
  const { promise, resolve, reject } = createDeferredPromise()

  // 分离创建编辑器的操作
  const createEditors = () => {
    const config = getEditorConfig()
    return new Promise((res) => {
      requestAnimationFrame(() => {
        try {
          inputEditor = CodeMirror.fromTextArea(inputSql.value, {
            ...config,
            value: defaultSQL
          })
          
          outputEditor = CodeMirror.fromTextArea(outputSql.value, {
            ...config,
            readOnly: true
          })
          res()
        } catch (err) {
          console.error('Editor creation failed:', err)
          reject(err)
        }
      })
    })
  }

  // 优化尺寸设置
  const setEditorSizes = () => {
    if (!inputEditor || !outputEditor) return

    return new Promise(res => {
      requestAnimationFrame(() => {
        inputEditor.setSize('100%', '300px')
        outputEditor.setSize('100%', '300px')
        
        // 使用 requestIdleCallback 进行刷新
        if ('requestIdleCallback' in window) {
          requestIdleCallback(() => {
            inputEditor.refresh()
            outputEditor.refresh()
            res()
          }, { timeout: 200 })
        } else {
          setTimeout(() => {
            inputEditor.refresh()
            outputEditor.refresh()
            res()
          }, 16)
        }
      })
    })
  }

  // 优化观察者设置
  const setupObservers = () => {
    if (!inputSql.value?.parentElement || !mounted) return

    const element = inputSql.value.parentElement
    const handleResize = rafThrottle(() => {
      if (mounted) setEditorSizes()
    })

    observer = new IntersectionObserver(
      entries => {
        const entry = entries[0]
        if (entry?.isIntersecting && mounted) {
          handleResize()
        }
      },
      { threshold: 0.1, rootMargin: '20px' }
    )

    resizeObserver = new ResizeObserver(handleResize)

    observer.observe(element)
    resizeObserver.observe(element)
  }

  // 初始化流程
  const initialize = async () => {
    try {
      mounted = true
      await createEditors()
      await setEditorSizes()
      setupObservers()
      
      // 移除自动格式化，只设置默认值
      inputEditor.setValue(defaultSQL)
      resolve()
      
      // 不再自动执行格式化
      // if ('requestIdleCallback' in window) {
      //   requestIdleCallback(() => {
      //     if (mounted) formatSQL()
      //     resolve()
      //   }, { timeout: 1000 })
      // } else {
      //   setTimeout(() => {
      //     if (mounted) formatSQL()
      //     resolve()
      //   }, 100)
      // }
    } catch (error) {
      reject(error)
    }
  }

  // 使用 requestIdleCallback 启动初始化
  if ('requestIdleCallback' in window) {
    requestIdleCallback(() => initialize(), { timeout: 2000 })
  } else {
    setTimeout(initialize, 0)
  }

  return promise
}

onMounted(async () => {
  mounted = true
  try {
    await initializeEditors()
  } catch (error) {
    console.error('Editor initialization failed:', error)
  }
})

// 优化 onUnmounted
onUnmounted(() => {
  mounted = false
  if (observer) {
    observer.disconnect()
    observer = null
  }
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
  if (inputEditor) {
    inputEditor.toTextArea()
    inputEditor = null
  }
  if (outputEditor) {
    outputEditor.toTextArea()
    outputEditor = null
  }
})

// 优化格式化函数
const formatSQL = rafThrottle(() => {
  if (!inputEditor) return
  
  const inputSQL = inputEditor.getValue()?.trim()
  if (!inputSQL) {
    ElMessage.warning('请输入SQL语句')
    return
  }

  try {
    const formattedSQL = format(inputSQL, {
      language: 'sql',
      indent: '    '
    })
    if (outputEditor) {
      outputEditor.setValue(formattedSQL)
      hasFormattedSQL.value = true
      ElMessage.success('格式化成功')
    }
  } catch (error) {
    ElMessage.error('SQL语句格式化失败，请检查语法')
  }
})

const copyResult = () => {
  if (!outputEditor) return
  
  const formattedSQL = outputEditor.getValue()
  navigator.clipboard.writeText(formattedSQL)
    .then(() => ElMessage.success('已复制到剪贴板'))
    .catch(() => ElMessage.error('复制失败，请手动复制'))
}

const goToHomepage = () => {
  router.push('/')
}
</script>

<style lang="scss" scoped>
.sql-formatter-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 10px; // 减小默认内边距
  box-sizing: border-box;
  overflow-y: auto;

  .formatter-container {
    max-width: 1200px;
    width: 96%; // 调整宽度占比
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 15px; // 稍微减小圆角
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
    padding: 20px; // 减小内边距
    box-sizing: border-box;
    margin: 10px auto;
    overflow-x: hidden;

    h1 {
      text-align: center;
      color: #4a5568;
      font-size: 24px; // 减小标题字体大小
      margin: 0 0 20px 0;
      text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
    }

    .editor-wrapper {
      margin-bottom: 15px; // 减小底部间距
      width: 100%;

      :deep(.CodeMirror) {
        height: 250px; // 调整默认高度
        border: 1px solid #dcdfe6;
        border-radius: 8px;
        font-size: 14px;
        line-height: 1.5;
        text-align: left; // 确保文本左对齐
        font-family: 'Courier New', Courier, monospace; // 使用等宽字体
        
        // 修复行号样式
        .CodeMirror-gutters {
          border-right: 1px solid #ddd;
          background-color: #f7f7f7;
          padding: 0 3px;
          height: 100%;
          box-sizing: border-box;
        }

        .CodeMirror-linenumber {
          padding: 0 5px 0 3px;
          min-width: 20px;
          text-align: right;
          color: #999;
          white-space: nowrap;
          box-sizing: border-box;
        }

        .CodeMirror-lines {
          padding: 4px 0; // 调整内容区域的内边距
          line-height: 1.5;
        }

        .CodeMirror-line {
          padding-left: 4px; // 调整每行代码的左边距
        }

        // 确保行号和代码内容对齐
        .CodeMirror-sizer {
          margin-left: 40px !important; // 调整这个值以确保足够的行号空间
        }

        .CodeMirror-gutter {
          min-width: 30px; // 确保行号区域有足够宽度
        }

        // 添加性能优化相关样式
        contain: content; // 开启内容隔离
        will-change: transform; // 优化滚动性能
        
        // 使用 transform 而不是 top/left 来提高性能
        transform: translateZ(0);
        backface-visibility: hidden;
        
        // 优化滚动性能
        &.native-scroll {
          overflow: overlay;
          -webkit-overflow-scrolling: touch;
          overscroll-behavior: contain;
          scroll-behavior: auto; // 改为 auto 以提高性能
        }

        // 优化合成层
        transform: translate3d(0, 0, 0);
        backface-visibility: hidden;
        
        // 优化重绘区域
        contain: layout style paint;

        // 修改滚动条样式
        :deep(.CodeMirror-scrollbar) {
          overflow: auto;
          
          &::-webkit-scrollbar {
            width: 8px;
            height: 8px;
          }
          
          &::-webkit-scrollbar-track {
            background: transparent;
          }
          
          &::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            
            &:hover {
              background: rgba(0, 0, 0, 0.2);
            }
          }
        }
      }
    }

    .el-form-item {
      margin-bottom: 20px; // 减小表单项间距

      :deep(.el-form-item__label) {
        font-size: 14px; // 减小标签字体大小
        padding-bottom: 5px; // 添加一些底部间距
      }

      .el-button {
        padding: 8px 15px; // 调整按钮内边距
      }
    }

    .description {
      padding: 15px;
      margin: 15px 0;
      font-size: 13px;
      text-align: left; // 添加左对齐
      background-color: #f0f5ff; // 添加背景色以区分区域
      border-radius: 8px; // 添加圆角

      h3 {
        font-size: 16px;
        margin: 0 0 10px 0;
        color: #4a5568; // 添加标题颜色
        text-align: left; // 确保标题也是左对齐
      }

      ol {
        padding-left: 20px; // 增加列表缩进
        margin: 0;
        text-align: left; // 确保列表项左对齐

        li {
          margin-bottom: 8px;
          line-height: 1.4;
          color: #666; // 添加文字颜色
          text-align: left; // 确保列表项内容左对齐
        }
      }
    }

    .button-group {
      gap: 10px;
      margin-top: 15px;

      .el-button {
        min-width: 100px; // 减小按钮最小宽度
      }
    }
  }
}

// 移动端优化
@media (max-width: 768px) {
  .sql-formatter-page {
    padding: 5px; // 进一步减小内边距

    .formatter-container {
      width: 98%; // 增加宽度占比
      padding: 12px; // 减小容器内边距
      margin: 5px auto;
      border-radius: 10px; // 减小圆角

      h1 {
        font-size: 20px; // 减小标题字体
        margin-bottom: 15px;
      }

      .editor-wrapper {
        :deep(.CodeMirror) {
          height: 200px; // 减小编辑器高度
          font-size: 13px; // 减小代码字体大小

          .CodeMirror-gutters {
            padding: 0 2px;
          }

          .CodeMirror-linenumber {
            padding: 0 3px;
            min-width: 16px;
          }

          .CodeMirror-sizer {
            margin-left: 35px !important; // 减小行号区域宽度
          }
        }
      }

      .el-form-item {
        margin-bottom: 15px;

        :deep(.el-form-item__label) {
          font-size: 13px;
        }
      }

      .description {
        padding: 10px;
        font-size: 12px;

        h3 {
          font-size: 14px;
          margin-bottom: 8px;
        }

        ol {
          padding-left: 12px;

          li {
            margin-bottom: 6px;
          }
        }
      }

      .button-group {
        flex-direction: column;
        gap: 8px;

        .el-button {
          width: 100%;
          margin: 0;
          padding: 8px;
          font-size: 13px;

          .el-icon {
            font-size: 14px;
          }
        }
      }
    }
  }
}

// 超小屏幕优化
@media (max-width: 320px) {
  .sql-formatter-page {
    .formatter-container {
      width: 100%;
      padding: 10px;
      margin: 0;
      border-radius: 0;

      h1 {
        font-size: 18px;
      }

      .editor-wrapper {
        :deep(.CodeMirror) {
          height: 180px;
          font-size: 12px;
        }
      }
    }
  }
}

// 添加响应式样式
@media (max-width: 768px) {
  .sql-formatter-page {
    padding: 10px;

    .formatter-container {
      padding: 15px;
      margin: 10px auto;

      h1 {
        font-size: 24px;
        margin-bottom: 20px;
      }

      .editor-wrapper {
        :deep(.CodeMirror) {
          height: 200px; // 在移动设备上减小高度
        }
      }

      .button-group {
        flex-direction: column;
        gap: 10px;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}

// 添加滚动优化样式
:deep(.CodeMirror-scroll) {
  overflow-x: auto !important;
  overflow-y: auto !important;
  will-change: transform;
  contain: content;
}

// 优化移动端滚动
@media (max-width: 768px) {
  .sql-formatter-page {
    .formatter-container {
      .editor-wrapper {
        :deep(.CodeMirror) {
          touch-action: manipulation;
          -webkit-tap-highlight-color: transparent;
        }
      }
    }
  }
}

// 添加全局样式优化
:deep(.CodeMirror-scroll) {
  contain: content;
  will-change: transform;
  transform: translateZ(0);
  backface-visibility: hidden;
  -webkit-font-smoothing: antialiased;
  
  // 使用 CSS 合成层
  @supports (transform: translate3d(0,0,0)) {
    transform: translate3d(0,0,0);
  }
}
</style>






